var express = require('express'),
  // swig = require('swig-templates'),
  request = require('request'),
  // wx = require('../base/wx'),
  router = express.Router();

/*
router.get('/', function(req, res, next) {
  wx.goAccessToken(req, res, function() {
    request.get({
      url: config.resourcePath.apiRoot + '/index/index/brandMobiles?user_id=' + (req.cookies.user_id ? req.cookies.user_id : '') + '&nav_id=' + req.query.id
    }, function(error, response, body) {
      try {
        var result = JSON.parse(body);
        if (result.code == 200) {
          var rundData = {
            title: result.title,
            phone: result.message
          };
          res.render('page/list', rundData);
        }
      } catch (e) {
        var err = new Error('Not Found');
        err.status = 500;
        next(err);
        return;
      }
    });
  });
});
*/

router.get('/', function(req, res, next) {
  if (parseInt(req.cookies.user_id) > 0) {    
    req.app.sync(function* (){
      let requestSync = req.app.async2sync(request.get);
      let result = yield requestSync({
        url: config.resourcePath.apiRoot + '/index/index/brandMobiles?user_id=' + req.cookies.user_id + '&nav_id=' + req.query.id,
        json: true
      });
      console.log(JSON.stringify(result));
      console.log(typeof result);
      // console.log(typeof result.index1);
      // console.log(typeof result.index2);
      if (result && result.code == 200) {
          var rundData = {
            title: result.title,
            phone: result.message
          };
          res.render('page/list', rundData);
        }
    }, 2);
  } else {
    // res.cookie('user_id', false, {
    //   maxAge: config.cookieTime,
    //   httpOnly: false
    // });
    res.clearCookie('user_id');
    res.redirect("/");

    // 上面的else 改成一个中间件统一处理cookie无效时的操作
    // next();
  }
});

module.exports = router;